/**
 * Created by wzl on 2017/5/1.
 */
import React,{Component} from 'react';
import {connect} from "react-redux";
import * as THREE from 'three';
import {loadMultipleTiles} from '../actions/actions';
import Tile from './Tile'

class TileManager extends Component {
    constructor(props){
        super(props);
        this.state={
            tiles:null
        }
    }
    componentWillMount(){
        console.log('tileManager will mount');
        this.props.dispatch(loadMultipleTiles(this.props.tiles));
    }
    // componentWillUpdate(nextProps, nextState){
    //     if(nextState.prevTiles!==nextProps.tiles){
    //         console.log('tile manager will update');
    //         this.setState({prevTiles:nextProps.tiles})
    //         this.props.dispatch(loadMultipleTiles(nextProps.tiles));
    //     }
    // }
    componentWillReceiveProps(nextProps) {
        // console.log(nextprops.tiles);
        if(this.props.tiles!==nextProps.tiles){
            nextProps.tiles.forEach((el,i)=>{
                let prev = this.props.tiles[i];
                if(prev) console.log(el.x,el.y,el.level,prev.x,prev.y,prev.level);
                else console.log(el.x,el.y,el.level);
            })
            console.log('tileManager will receive new tiles');
            this.props.dispatch(loadMultipleTiles(nextProps.tiles));
        }
        if(nextProps.load.result && nextProps.scene && nextProps.load.result!==this.props.load.result) {
            let scene=nextProps.scene;
            let tilesGroup = new THREE.Object3D();
            let data=nextProps.load.result;
            let tiles=data.map((item,i)=>{
                let tile = nextProps.tiles[i];
                let key = `${tile.x}${tile.y}${tile.level}`;
                return (
                    <Tile tilesGroup={tilesGroup}
                          tile={nextProps.tiles[i]}
                          data={item}
                          // tileShouldUpdate={nextprops.tileShouldUpdate}
                          key={key}/> //****这里才是重点，每一个key都是唯一的，如果key，所以要给每一个tile设置唯一的key
                )
            });
            scene.add(tilesGroup);
            this.setState({tiles:tiles});
        }
    }
    componentDidUpdate(){
        console.log('tile manger did update');
        this.props.tileShouldUpdate();
    }
    render(){
        if(this.state.tiles){
            console.log('render content in tileManager');
            return (<span>{this.state.tiles}</span>);
        }
        else{
            return null;
        }
    }
}

export default TileManager = connect((store) => {
    return {
        load: store.load
    }
})(TileManager)